package com.zj.core.services

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.AsyncTask
import android.os.Environment
import com.dialogutils.Notifications
import com.dialogutils.ToastUtil
import com.log.Logger
import com.zj.core.base.BaseApplication
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.InputStream
import java.net.URL
import java.net.URLConnection
import android.os.Handler
import android.os.Looper

class DownloadService(context: Context?) : AsyncTask<Unit, Int, Boolean>(){
    @SuppressLint("StaticFieldLeak")
    private var mContext:Context?=context
    private var notifiInstance:Notifications?=null

    private var fileNotFound:Boolean=true         //文件是否存在
    private var fileName="test.pdf"
    private var fileUrl=""
    private var filePath=Environment.getExternalStorageDirectory().toString() +File.separator

    /**
     * 测试使用
     */
    companion object{
        var FILE_NAME = "test.pdf"                       //下载文件的名称
        var FILE_URL="http://clfile.imooc.com/class/assist/118/1328281/AsyncTask.pdf"
        var FILE_PATH=Environment.getExternalStorageDirectory().toString() +File.separator
    }

    fun setFileUrl(url:String): DownloadService {
        fileUrl=url
        return this
    }

    fun setFileSavePath(path:String): DownloadService {
        filePath=path
        return this
    }

    fun setFileSaveName(name:String): DownloadService {
        fileName=name
        return this
    }

    override fun onPreExecute(){
        notifiInstance=Notifications(mContext)
            .setContentTitle(fileName.split(".")[0])
            .setContentText("下载中")
    }

    /**
     * 后台执行任务
     */
    override fun doInBackground(vararg params: Unit?): Boolean?{
        var inPutStream: InputStream? =null

        notifiInstance?.showNotifi(mContext)

        val urlConnection: URLConnection =URL(fileUrl).openConnection()
        try{
            inPutStream =urlConnection.getInputStream()
        }catch (e: FileNotFoundException){
            fileNotFound=false
            Handler(Looper.getMainLooper()).post { ToastUtil.showShort(BaseApplication.context,"下载文件未找到") }
        }
        val contentLength:Long= urlConnection.contentLength.toLong()

        val path=File(filePath)
        if(!path.exists()){
            path.mkdirs()
        }

        File(filePath+fileName).apply {
            if(exists()){
                val result:Boolean=delete()
                if(!result){
                    Logger.debug("TAG","文件冲突，删除失败")
                    return false
                }
            }
        }

        val bytes = ByteArray(1024)
        var downloadSize:Long= 0
        var length: Int
        val outputStream=FileOutputStream(filePath+fileName)

        inPutStream?.let {
            length=it.read(bytes)
            while (length!=-1){
                outputStream.write(bytes, 0, length)
                downloadSize += length
                notifiInstance?.updateNotifi((downloadSize*100/contentLength).toInt())
                length=it.read(bytes)
            }
            it.close()
        }

        outputStream.close()
        return true
    }

    /**
     * 获取后台执行进度
     * 可操作UI
     */
    override fun onProgressUpdate(vararg values: Int?){}

    /**
     * 后台任务执行完成
     * 可操作UI
     */
    override fun onPostExecute(aBoolean: Boolean?){
        notifiInstance?.cancelNotifi()

        if(fileNotFound){
            Intent("com.zj.datacoll.install").apply {
                putExtra("filePath",filePath)
                putExtra("fileName",fileName)
                mContext?.sendBroadcast(this)
            }
        }
    }
}
